<?php

namespace addons\cms\controller\wxapp;

use addons\cms\model\Archives as ArchivesModel;
use addons\cms\model\Channel;
use addons\cms\model\Comment;
use addons\cms\model\Modelx;
use addons\cms\model\Archives_user;
use think\Validate;
use app\common\library\Auth;
use addons\cms\model\User_follow;
use think\Db;
use think\Cache;
use fast\Http;

/**
 * 文档
 */
class Archives extends Base
{

    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 读取文档列表
     */
    public function index()
    {
        $params = [];
        $model = (int)$this->request->request('model');
        $channel = (int)$this->request->request('channel');
        $page = (int)$this->request->request('page');
        $selectedId = $this->request->request('selectedId');
        $see_id = $this->request->request('see_id');

        if ($model) {
            $params['model'] = $model;
        }
        if ($channel) {
            $params['channel'] = $channel;
        }
        if ($selectedId != '' && $selectedId == 0) {
            $params['user_id'] = $this->auth->id;
            $params['selectedId'] = $selectedId;
        }else{
            $params['open'] = 1;
        }

        if ($selectedId == 1) {
            $follow_id = User_follow::where('user_id', $this->auth->id)
                ->select();
            $follow_id = collection($follow_id)->toArray();
            $fw_user_id = '';
            foreach ($follow_id as $k=>$v){
                $fw_user_id.= ','.$v['follow_id'];
            }
            $fw_user_id = trim($fw_user_id,',');
            $params['user_id'] = $fw_user_id;
            $params['selectedId'] = $selectedId;
        }

        if ($see_id) {
            $params['user_id'] = $see_id;
        }
        $page = max(1, $page);
        $params['limit'] = ($page - 1) * 10 . ',10';

        $tabList2 = Channel::where('status', 'normal')
            ->where('parent_id', $channel)
            ->where('type', 'in', ['list'])
            ->order('weigh desc,id desc')
            ->cache(false)
            ->select();
        $tabList2 = collection($tabList2)->toArray();
        $tabList2_count = count($tabList2);
        foreach ($tabList2 as $k=>$v){
            $image= 'https://'.$_SERVER['SERVER_NAME'].$v['image'];
            $tabList2[$k]['image'] = $image;
        }

        $list = ArchivesModel::getArchivesList($params);

        //获取最新三条评论
        foreach ($list as $k=>$v){
            if(substr($v['user']['avatar'],0,5) != 'https'){
                $avatar = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$v['user']['avatar'];
                $list[$k]['user']['avatars'] = $avatar;
            }else{
                $list[$k]['user']['avatars'] = $v['user']['avatar'];;
            }
            if(substr($v['image'],strrpos($v['image'],'/')+1) == 'noimage.jpg'){
                unset($list[$k]['image']);
            }
            $channelParent = Channel::where('id',$v['channel']['parent_id'])->find();
            if ($channelParent) {
                $list[$k]['parentNeme'] = $channelParent['name'];
            }
            $commentList = Comment::getCommentList(['aid' => $v['id']]);
            $list[$k]['comment'] = $commentList->getCollection();

            $is_follow = User_follow::where('user_id', $this->auth->id)
                ->where('follow_id', $v['user_id'])
                ->select();
            if($is_follow){
                $list[$k]['user']['follow'] = '取消关注';
            }else{
                $list[$k]['user']['follow'] = '关注';
            }
        }
        $userInfo = '';
        if ($see_id && $list) {
            $list = collection($list)->toArray();
            $userInfo = $list[0]['user'];
            $userInfo['user_id'] =  $userInfo['id'];
            $userInfo['u_count'] = User_follow::where('user_id', $userInfo['user_id'])
                ->count();
            $userInfo['f_count'] = User_follow::where('follow_id', $userInfo['user_id'])
                ->count();
            $userInfo['archives_count'] = ArchivesModel::where('user_id', $userInfo['user_id'])
                ->where(['deletetime'=> ['exp', Db::raw('IS NULL')]])
                ->where('status', 'normal')
                ->count();
        }

        $this->success('', ['archivesList' => $list,'tabList2' => $tabList2, 'tabList2_count' => $tabList2_count,'userInfo' => $userInfo,]);
    }

    public function cate()
    {
        $tabList2 = Channel::where('status', 'normal')
            ->where('parent_id',0)
            ->where('type', 'channel')
            ->order('weigh desc,id desc')
            ->cache(false)
            ->select();

        $tabList2_childs = [];
        foreach ($tabList2 as $k=>$v){
            $tabList2_child = Channel::where('status', 'normal')
                ->where('parent_id',$v['id'])
                ->where('type', 'list')
                ->order('weigh desc,id desc')
                ->cache(false)
                ->select();
            foreach ($tabList2_child as $kk=>$vv){
                $arr = [];
                $arr['id'] = $vv['id'];
                $arr['name'] = $tabList2[$k]['name'] .'-' .$tabList2_child[$kk]['name'];
                array_push($tabList2_childs,$arr);
            }
        }
        $this->success('', ['tabList2' => $tabList2_childs]);
    }

    /**
     * 发表文章
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function post()
    {
        $id = $this->request->get('id');
        $archives = $id ? \app\admin\model\cms\Archives::get($id) : null;

        if ($archives) {
            $channel = Channel::get($archives['channel_id']);
            if (!$channel) {
                $this->error(__('未找到指定栏目'));
            }
            $model = \addons\cms\model\Modelx::get($channel['model_id']);
            if (!$model) {
                $this->error(__('未找到指定模型'));
            }
            if ($archives['user_id'] != $this->auth->id) {
                $this->error("无法进行越权操作！");
            }
        } else {
            $model = null;
            $model_id = $this->request->request('model_id');
            // 如果有model_id则调用指定模型
            if ($model_id) {
                $model = Modelx::get($model_id);
            }
        }

        // 如果来源于提交
        if ($this->request->isPost()) {
            $auth = Auth::instance();

            if (!$auth->id) {
                $this->error("请登录后发表文章");
            }
            $row['__token__'] = $this->request->post('token');
            $row['title'] = $this->request->post('title');
            $row['channel_id'] = $this->request->post('channel_id');
            $row['content'] = str_replace('&nbsp;','',$_POST['content']);
            $row['description'] = mb_substr(str_replace('&nbsp;','',$this->request->post('content')),0,100);
            $row['open'] = $this->request->post('open');
            $row['open'] = $row['open']=='是' ? 1 : 0;
            $row['region'] = $this->request->post('region');
            $row['voiceUrl'] = $this->request->post('voiceUrl');

            $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
            preg_match($pattern,$row['content'],$match);
            if($match){
                $row['image'] = $match[1];
            }

            //微信内容安全检测
            $res = $this->msgSecCheck($row['content']);
            if($res['errcode'] != 0){
                $this->error($res['errmsg']);
            }

            $rule = [
                'title|标题'      => 'require|length:3,100',
                'channel_id|栏目' => 'require|integer',
                'content|内容'    => 'require',
                '__token__'     => 'token',
            ];

            $msg = [
                'title.require'   => '标题不能为空',
                'title.length'    => '标题长度限制在3~100个字符',
                'channel_id'      => '栏目不能为空',
                'content.require' => '内容不能为空',
            ];

            $row['user_id'] = $this->auth->id;
            $row['status'] = 'pulloff';
            try {
                if ($archives) {
                    $archives->allowField(true)->save($row);
                } else {
                    (new \app\admin\model\cms\Archives)->allowField(true)->save($row);
                }
            } catch (Exception $e) {
                $this->error("发生错误:" . $e->getMessage());
            }
            $this->success("发布成功！请等待审核!");
            exit;
        }

        // 合并主副表
        if ($archives) {
            $addon = db($model['table'])->where('id', $archives['id'])->find();
            if ($addon) {
                $archives = array_merge($archives->toArray(), $addon);
            }
        }

        $channel = new Channel();
        if ($model) {
            $channel->where('model_id', $model['id']);
        }
        // 读取可发布的栏目列表
        $disabledIds = [];
        $channelList = collection(
            $channel->where('type', '<>', 'link')
                ->where("((type='list' AND iscontribute='1') OR type='channel')")
                ->order("weigh desc,id desc")
                ->cache(false)
                ->select()
        )->toArray();
        $channelParents = [];
        foreach ($channelList as $index => $item) {
            if ($item['parent_id']) {
                $channelParents[] = $item['parent_id'];
            }
        }
        foreach ($channelList as $k => $v) {
            if ($v['type'] != 'list') {
                $disabledIds[] = $v['id'];
            }
            if ($v['type'] == 'channel' && !in_array($v['id'], $channelParents)) {
                unset($channelList[$k]);
            }
        }
        $tree = Tree::instance()->init($channelList, 'parent_id');
        $channelOptions = $tree->getTree(0, "<option value=@id @selected @disabled>@spacer@name</option>", $archives ? $archives['channel_id'] : '', $disabledIds);
        $this->view->assign('channelOptions', $channelOptions);
        $this->view->assign([
            'archives'       => $archives,
            'channelOptions' => $channelOptions,
            'categoryList'   => ''
        ]);
        $this->assignconfig('archives_id', $archives ? $archives['id'] : 0);

        $modelName = $model ? $model['name'] : '文章';
        $this->view->assign('title', $archives ? "修改{$modelName}" : "发布{$modelName}");
        $this->view->assign('model', $model);
        return $this->view->fetch();
    }

    /*微信文字敏感内容检测*/
    public function msgSecCheck($msg)
    {
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$token";
        $info = Http::sendRequest($url,json_encode(['content'=>$msg]));
        return json_decode($info['msg'],true);
    }

    public function getAccessToken(){
        $config = get_addon_config('cms');

        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $config['wxappid']."&secret=".$config['wxappsecret']; //微信给出的获取access_token的接口
        $access_token=Cache::get($this->auth->id."_access_token");
        //查询缓存中是否已存在access_token
        if($access_token==""){
            //访问接口获取access_token
            $res = json_decode(file_get_contents($url));
            $access_token = $res->access_token;
            //设置缓存，过期时间2小时
            Cache::set($this->auth->id."_access_token",$access_token,$res->expires_in);
        }
        return $access_token;
    }

    public function detail()
    {
        $action = $this->request->post("action");
        if ($action && $this->request->isPost()) {
            return $this->$action();
        }
        $diyname = $this->request->param('diyname');
        if ($diyname && !is_numeric($diyname)) {
            $archives = ArchivesModel::getByDiyname($diyname);
        } else {
            $id = $diyname ? $diyname : $this->request->request('id', '');
            $archives = ArchivesModel::get($id);
        }
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $channel = Channel::get($archives['channel_id']);
        if (!$channel) {
            $this->error(__('No specified channel found'));
        }
        $channelParent = Channel::where('id',$channel['parent_id'])->find();
        if ($channelParent) {
            $channel['parentNeme'] = $channelParent['name'];
        }
        $model = Modelx::get($channel['model_id']);
        if (!$model) {
            $this->error(__('No specified model found'));
        }
        $archives->setInc("views", 1);
        $addon = db($model['table'])->where('id', $archives['id'])->find();
        if ($addon) {
            if ($model->fields) {
                $fieldsContentList = $model->getFieldsContentList($model->id);
                //附加列表字段
                array_walk($fieldsContentList, function ($content, $field) use (&$addon) {
                    $addon[$field . '_text'] = isset($content[$addon[$field]]) ? $content[$addon[$field]] : $addon[$field];
                });
            }
            $archives->setData($addon);
        } else {
            $this->error(__('No specified article addon found'));
        }
        $archives = array_merge($archives->toArray(), $addon);
        $commentList = Comment::getCommentList(['aid' => $archives['id']]);

        $is_collection = Archives_user::where(['archives_id'=>$archives['id'],'user_id'=>$this->auth->id])->find();
        if($is_collection){
            $archives['is_collection'] = 1;
        }else{
            $archives['is_collection'] = 0;
        }
        $this->success('', ['archivesInfo' => $archives, 'channelInfo' => $channel, 'commentList' => $commentList->getCollection()]);
    }

    /**
     * 赞与踩
     */
    public function vote()
    {
        $id = (int)$this->request->post("id");
        $type = trim($this->request->post("type", ""));
        if (!$id || !$type) {
            $this->error(__('Operation failed'));
        }
        $archives = ArchivesModel::get($id);
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $archives->where('id', $id)->setInc($type === 'like' ? 'likes' : 'dislikes', 1);
        \addons\cms\model\Msg::postMsg(4,$id,0);
        $archives = ArchivesModel::get($id);
        $this->success(__('Operation completed'), ['likes' => $archives->likes, 'dislikes' => $archives->dislikes, 'likeratio' => $archives->likeratio]);
    }

    /**
     * 收藏
     */
    public function collection()
    {
        $id = (int)$this->request->post("id");
        $type = trim($this->request->post("type", ""));
        if (!$id || !$type) {
            $this->error(__('Operation failed'));
        }
        $archives = ArchivesModel::get($id);
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $archives = ArchivesModel::get($id);

        $archives_user = Archives_user::postComment($id);
        if($archives_user['code'] == -1){
            $this->error(__($archives_user['msg']));
        }
        $archives->where('id', $id)->setInc('collection', 1);
        \addons\cms\model\Msg::postMsg(3,$id,0);
        $archives = ArchivesModel::get($id);
        $this->success(__('Operation completed'), ['collection' => $archives->collection]);
    }


    /**
     * 取消收藏
     */
    public function qu_collection()
    {
        $id = (int)$this->request->post("id");
        if (!$id) {
            $this->error(__('Operation failed'));
        }
        $archives = ArchivesModel::get($id);
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $archives = ArchivesModel::get($id);

        $archives_user = Archives_user::qu_collection($id);
        if($archives_user['code'] == -1){
            $this->error(__($archives_user['msg']));
        }
        $archives->where('id', $id)->setInc('collection', -1);
        $archives = ArchivesModel::get($id);
        $this->success(__('Operation completed'), ['collection' => $archives->collection]);
    }

    /**
     * 删除文章
     */
    public function del()
    {
        $aid = (int)$this->request->post("aid");
        if (!$aid) {
            $this->error(__('Operation failed'));
        }

        $archives_user = ArchivesModel::delArchives($aid);
        if($archives_user['code'] == -1){
            $this->error(__($archives_user['msg']));
        }
/*        \addons\cms\model\Msg::postMsg(2,0,$aid,0);*/

        $this->success(__('Operation completed'), [ 'code'=>1, 'msg'=>"删除成功"]);
    }

}
